from django.shortcuts import render, HttpResponse, redirect
from myapp.models import User
from myapp.models import IdCard
from myapp.models import Project,App,Server
from pythonorm.main import self_login_required

def user_add(request):
    if request.method == "GET":
        return render(request, 'user_add.html')
    elif request.method == "POST":
        try:
            # 获取前端提交的数据
            user = request.POST.get("user")
            name = request.POST.get("name")
            sex = request.POST.get("sex")
            age = request.POST.get("age")
            label = request.POST.get("label")
            number = request.POST.get("number")
            address = request.POST.get("address")
            obj = User(
                user=user,
                name=name,
                sex=sex,
                age=age,
                label=label
            )
            obj.save()
            IdCard.objects.create(user=obj, number=number, address=address)

            msg = "用户添加成功."
            code = 0
        except:
            msg = "用户添加失败！"
            code = 1  # 自定义

    return render(request, 'user_add.html', {'msg': msg, 'code': code})

def user_list(request):
    user_list = User.objects.all() # 所有记录
    return render(request, "user_list.html", {'user_list': user_list})

def api(request):
    obj = User.objects.all() # queryset对象
    #json_data = serializers.serialize('json', obj)

    import json
    obj = User.objects.all()
    l = [] # [{},{}]
    for i in obj:
        d = {}
        d['name'] = i.name
        d['user'] = i.user
        d['sex'] = i.sex
        d['age'] = i.age
        d['label'] = i.label
        l.append(d)
    json_data = json.dumps(l)

    return HttpResponse(json_data)


def app(request):
    app_list = App.objects.all()
    return render(request, 'app.html', {'app_list': app_list})

@self_login_required
def project(request):
    project_list = Project.objects.all()
    return render(request, 'project.html', {'project_list': project_list})

@self_login_required
def app_add(request):
    if request.method == "GET":
        project_list = Project.objects.all()
        server_list = Server.objects.all()
        return render(request, 'app_add.html', {'project_list': project_list,'server_list': server_list})
    elif request.method == "POST":
        print(request.POST)
        app_name = request.POST.get("app-name")
        app_describe = request.POST.get("app-describe")
        project_name = request.POST.get("project-name")
        server_list = request.POST.getlist("server-list")  # 使用getlist获取，用于获取表单多少值，列表形式

        # 用于项目选择和服务器选择
        # project_list = Project.objects.all()
        # server_list = Server.objects.all()

        # 后端验证字段可用性
        if not app_name:
            msg = "字段不能为空"
            return render(request, 'app_add.html')

        try:
            project_obj = Project.objects.get(name=project_name)
            app = App.objects.create(name=app_name, describe=app_describe, project=project_obj)

            # 将服务器（可能多个）关联应用
            print(server_list)
            for server in server_list:
                server = Server.objects.get(hostname=server)
                server.app.add(app)

            msg = "添加成功"
            code = 0
        except:
            msg = "添加失败"
            code = 1

        return redirect(app_add)
        #return render(request, 'app_add.html', {'project_list': project_list,'server_list': server_list, 'msg': msg, 'code': code})

@self_login_required
def server(request):
    server_list = Server.objects.all()
    return render(request, 'server.html', {'server_list': server_list})

@self_login_required
def app_server(request):
    app_list = App.objects.all()
    return render(request, 'app_server.html', {'app_list': app_list})